package com.bwie.home.backstage.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.home.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.bwie.home.backstage.entity.UserEntity;
import com.bwie.home.backstage.service.UserService;
import com.bwie.home.common.utils.PageUtils;
import com.bwie.home.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author sy
 * @email sunlightcs@gmail.com
 * @date 2021-09-10 09:46:41
 */
@RestController
@RequestMapping("backstage/user")
//@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 账号密码登录
     */
    @PostMapping("/loginByPwd")
    public R loginByPwd(@RequestBody UserEntity userEntity){
        UserEntity one = userService.getOne(new QueryWrapper<UserEntity>().eq("user_name", userEntity.getUserName())
                .eq("user_pwd", userEntity.getUserPwd()));
        if (one!=null){
            return R.ok("登录成功").put("user",one);
        }
        return R.error(5000,"登录失败");
    }

    /**
     * 列表 人员管理
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,@RequestBody UserEntity userEntity){
        R page = userService.queryPage(params,userEntity);
        return R.ok(page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    public R info(@PathVariable("userId") Integer userId){
		UserEntity user = userService.getById(userId);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestParam("phone") String phone,@RequestParam("code") String code,@RequestBody UserEntity user){
        //将redis中对应的手机号验证器取出
        String yan = redisTemplate.opsForValue().get(phone);
        //判断 前台输入的验证码和 redis验证码进行比较
        if (yan.equals(code)){ //如果一样添加
            user.setUserState(1);
            userService.save(user);
        }else {  //不一样失败
            return R.error(1,"1");
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] userIds){
		userService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }


    /**
     *  手机号验密码登录
     */
    @RequestMapping("/login")

    public R phoneLogin(@RequestBody UserEntity userEntity, HttpServletRequest request, HttpServletResponse response){
        //前台传来的验证码手机号 进行验证
        UserEntity userEntity1= userService.phoneLogin(userEntity,request,response);
        System.out.println(userEntity1);
        //判断 对象中的手机号密码
        if (userEntity1!=null){
            //每次登录是时候 更新 最近登录的时间
            userEntity1.setUserLastdate(new Date());
            userService.updateById(userEntity1);
            // 每次登录的时候 生成token
            String admin = jwtUtil.createJWT(userEntity1.getUserId().toString(), userEntity1.getUserPhone(), "admin");
            System.out.println(admin);
            //将登录的信息 token 返给前台
            return Objects.requireNonNull(R.ok().put("token", admin)).put("data",userEntity1);
        }
        return null;

    }

    /**
     *  手机号登录
     */
    @RequestMapping("/phone")
    public R phone(@RequestParam("phone") String phone,@RequestParam("code") String code){
        UserEntity userEntity=userService.phone(phone,code);
        //将redis中对应的手机号验证器取出
        String yan = redisTemplate.opsForValue().get(phone);
        //判断手机号不为null 前台输入的验证 和redis中验证码进行比较
        if (userEntity != null && yan != null) {
            if (yan.equals(code)) {
                String admin = jwtUtil.createJWT(userEntity.getUserId().toString(), userEntity.getUserPhone(), "admin");
                return R.ok().put("token", admin).put("aa", userEntity).put("code", code);
            }
        }
        return null;
    }


    /**
     * 获取验证码
     */
    @RequestMapping("/yan")
    public R yan(String phone){
        //前台输入手机号 获取验证码
        String phone1 = Phone.Phone(phone);
        //将获取到的验证码存入redis中 设置过期时间60秒钟自动删除
        redisTemplate.opsForValue().set(phone,phone1,3600, TimeUnit.SECONDS);
        return R.ok().put("yan",phone1);
    }

}
